from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from note.models import Note
from note_dir.serializers import NoteDirSerializer
from note_dir.models import NoteDir
from user.models import User


class NoteDirViewSet(ModelViewSet):
    """
    笔记目录视图集

    list:
        获取全部笔记目录
    create:
        新建笔记目录
    retrieve:
        查看笔记目录
    update:
        笔记目录重命名
    destroy:
        删除笔记目录（伪删除，目录下的笔记自动回收）
    """

    queryset = NoteDir.objects.filter(is_delete=False)
    serializer_class = NoteDirSerializer

    def create(self, request, *args, **kwargs):
        """新建笔记目录"""
        uid = request.session.get('uid')
        if not uid or not User.objects.filter(id=uid).first():
            raise ValidationError({'usre_id': ['用户ID错误。']})
        title = request.data.get('title')
        dir = NoteDir.objects.create(title=title, user_id=uid)
        return Response(NoteDirSerializer(dir).data, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        """修改笔记名称"""
        dir = self.get_object()
        if dir:
            title = request.data.get('title')
            if title:
                dir.title = title
                dir.save()
                return Response(NoteDirSerializer(dir).data)
        return Response(status=status.HTTP_404_NOT_FOUND)

    def destroy(self, request, *args, **kwargs):
        """删除笔记目录（伪删除，目录下的笔记自动回收）"""
        instance = self.get_object()
        notes = Note.objects.filter(dir_id=instance.id)
        for note in notes:
            note.is_delete = True
            note.save()
        instance.is_delete = True
        instance.save()
        return Response(status=204)
